package cn.e3mall.order.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.e3mall.cart.service.CartService;
import cn.e3mall.common.utils.CookieUtils;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.sso.service.TokenService;

public class LoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	private TokenService tokenService;
	@Autowired
	private CartService cartService;
	
	@Value("${SSO_LOGIN_URL}")
	private String SSO_LOGIN_URL;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/**
		 * 	1.判断用户是否登录
		 * 	2.未登录就跳转到登录页面
		 * 	3.登录就放行
		 * 		>从cookie取token
		 * 		>token不存在则未登录
		 * 		>token存在就调用sso服务查看token是否过期
		 * 		>过期就跳转到登录页面
		 * 		>未过期就把用户信息保存到reqiest中
		 * 		>在登录状态跳转到订单页面前，把cookie中的购物车和redis的购物车合并
		 */
		//取token
		String token = CookieUtils.getCookieValue(request, "token");
		//token不存在
		if(StringUtils.isBlank(token)) {
			//重定向登录界面
			response.sendRedirect(SSO_LOGIN_URL+"?redirect="+request.getRequestURL());
			System.out.println(request.getRequestURL());
			//拦截
			return false;
		}
		
		//调用sso服务查看token是否过期
		E3Result result = tokenService.getUserInfoByToken(token);
		
		//过期则重定向到登录界面
		if(result.getStatus() != 200) {
			//重定向登录界面
			response.sendRedirect(SSO_LOGIN_URL+"?redirect="+request.getRequestURI());
			//拦截
			return false;
		}
		
		//用户信息存在，则登录状态
		//把用户信息放到request域中
		TbUser user = (TbUser) result.getData();
		request.setAttribute("user", user);
		
		//合并购物车
		String cartList = CookieUtils.getCookieValue(request, "cart");
		//购物车不空
		if(StringUtils.isNotBlank(cartList)) {
			List<TbItem> list = JsonUtils.jsonToList(cartList, TbItem.class);
			cartService.mergeCart(user.getId(), list);
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
